package com.reason.chat.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reason.chat.Config.CustomSpringConfigurator;
import com.reason.chat.Mapper.FriendMapper;
import com.reason.chat.pojo.Afriend;
import com.reason.chat.pojo.Friend;
import com.reason.chat.pojo.To;
import com.reason.chat.service.ChatService;
import com.reason.chat.service.WebSocektService;
import com.reason.chat.service.impl.ChatServiceimpl;
import com.reason.chat.service.impl.WebSocketServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 熊钒汐
 * @date 2020/6/30 9:20
 */
@Component
@ServerEndpoint(value = "/chat/{id}",configurator = CustomSpringConfigurator.class)
public class WebSocketController {
    /**用于存储所有用户在线数据*/
    private static ConcurrentHashMap<String, WebSocketController> webSocketSet = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**指定的sid，具有唯一性，暫定為用戶的昵称*/
    private String sid = "";

    WebSocektService webSocektService=new WebSocketServiceimpl();
    ChatService chatService=new ChatServiceimpl();
    @Autowired
    FriendMapper friendMapper;
    /**新建链接*/
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session, EndpointConfig config) {

        this.session = session;
        this.sid = id;
        //加入set中
        webSocketSet.put(sid, this);
    }
    /**断开链接*/
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
    }
    /**获取前台发送信息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        Map map=JSON.parseObject(message,Map.class);
        if("send".equals(map.get("type")))
        {
            To to= webSocektService.Socketto(message);
            try {
                sendtoUser(message, String.valueOf(to.getId()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if("status".equals(map.get("type")))
        {
            Map socketstatus = webSocektService.Socketstatus(map);
            this.sendStatus(socketstatus);
        }else if("add".equals(map.get("type")))
        {
            Long uid=Long.valueOf(String.valueOf(map.get("uid")));
            Long fid=Long.valueOf(String.valueOf(map.get("fid")));
            Afriend afriend = chatService.getAfriend(uid,fid);
            Map socketadd = webSocektService.Socketadd(afriend);
            addfriend(String.valueOf(JSON.toJSON(socketadd)),uid,fid);
        }

    }
    /**信息错误*/
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    /**发送聊天信息*/
    public boolean sendtoUser(String message, String sendUserId) throws IOException {
        Map socketminemap = webSocektService.Socketmine(message);
            if (webSocketSet.get(sendUserId) != null) {
                {
                    webSocketSet.get(sendUserId).sendMessage(String.valueOf( JSON.toJSON(socketminemap)));
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            } else {
                this.senderror(message);
                return false;
            }
    }
    /**发送不在线信息*/
    public void senderror(String message)
    {System.out.println(message);
        Map errormap = webSocektService.Socketmine(message);
        Map socketerror = webSocektService.Socketerror(message);

        try {
            webSocketSet.get("15102161197").sendMessage(String.valueOf( JSON.toJSON(socketerror)));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void addfriend(String message,Long uid,Long fid)
    {

        try { webSocketSet.get(uid).sendMessage(String.valueOf( JSON.toJSON(message)));
            Friend friend=new Friend();
            friend.setUserid(uid);
            friend.setFriendid(fid);
            friendMapper.insert(friend);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**发送状态到前台页面*/
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    public void sendStatus(Map map)
    {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("friendid",Long.valueOf(String.valueOf(map.get("id"))));
        List<Friend> list = friendMapper.selectList(queryWrapper);
        for (String s : webSocketSet.keySet()) {
            for (Friend friend : list) {
                if(Long.valueOf(s).equals(friend.getUserid()))
                {
                    try {
                        webSocketSet.get(s).sendMessage(String.valueOf(JSON.toJSON(map)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
